package com.whstudio.util.thread;

public class KeepTomcatAlive {
	public KeepTomcatAlive(){
		Keeper keeper=new Keeper();
		keeper.start();
	}
	
	class Keeper extends Thread{
		public Keeper(){
			
		}
		
		public void run(){
			while(true){
				keepTomcatAlive();
				try {
					sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public void keepTomcatAlive(){
			String s;
			String t = new String("tomcat6.exe");
			boolean isTomcatAlive = false;
			try {
				java.lang.Process p = java.lang.Runtime.getRuntime().exec(
						"tasklist");
				java.io.BufferedReader in = new java.io.BufferedReader(
						new java.io.InputStreamReader(p.getInputStream()));
				while ((s = in.readLine()) != null) {
					if (s.startsWith(t)){
						isTomcatAlive = true;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("isTomcatAlive:"+isTomcatAlive);
			if (!isTomcatAlive){
				restartTomcat();
			}
		}
		
		public void restartTomcat() {
			try {
				java.lang.Runtime.getRuntime().exec("cmd /c C:\\Tomcat\\bin\\tomcat6.exe");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		new KeepTomcatAlive();
	}
}
